from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Dict, Any

mcp = FastMCP("GDK-Pixbuf2 MCP Server")

"""
面向软件：gdk-pixbuf2（GDK Pixbuf图像处理库）

MCP tools 列表：
1. gdk_pixbuf_rotate_image
   - 用途：使用gdk-pixbuf2旋转图像文件
   - 参数：
     * input_file: str - 输入图像文件路径
     * output_file: str - 输出图像文件路径
   - 返回JSON结构：
     {
       "success": bool,
       "command": str,
       "exit_code": int,
       "stdout": str,
       "stderr": str
     }
"""

@mcp.tool()
def gdk_pixbuf_rotate_image(input_file: str, output_file: str) -> Dict[str, Any]:
    """
    使用gdk-pixbuf2旋转图像文件
    
    参数:
        input_file: 输入图像文件路径
        output_file: 输出图像文件路径
        
    返回:
        包含执行结果的JSON对象，结构为：
        {
          "success": bool,
          "command": str, 
          "exit_code": int,
          "stdout": str,
          "stderr": str
        }
    """
    try:
        # 构建旋转图像的Python命令
        rotate_script = """
import gi
gi.require_version('GdkPixbuf', '2.0')
from gi.repository import GdkPixbuf
import sys

if len(sys.argv) != 3:
    print("Usage: python3 script.py input.jpg output.jpg")
    sys.exit(1)

input_file = sys.argv[1]
output_file = sys.argv[2]

try:
    # 加载图像
    pixbuf = GdkPixbuf.Pixbuf.new_from_file(input_file)
    
    # 旋转图像（这里使用90度旋转作为示例）
    rotated_pixbuf = pixbuf.rotate_simple(GdkPixbuf.PixbufRotation.CLOCKWISE)
    
    # 保存旋转后的图像
    rotated_pixbuf.savev(output_file, "jpeg", [], [])
    print(f"Successfully rotated {input_file} to {output_file}")
    
except Exception as e:
    print(f"Error: {e}")
    sys.exit(1)
"""
        
        # 执行Python脚本进行图像旋转
        cmd = ["python3", "-c", rotate_script, input_file, output_file]
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": "Command timed out after 30 seconds"
        }
    except Exception as e:
        return {
            "success": False,
            "command": "python3 rotate_image.py",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Unexpected error: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()